package com.cjx.leetcode.backtracking;

import java.util.*;

/**
 * @author cjx
 * @description E47.全排列Ⅱ【中】
 * @createDate 2024/4/6 10:20
 **/
public class E47 {

    private final List<List<Integer>> result = new ArrayList<List<Integer>>();
    private final List<Integer> path = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        backtracking(nums, used);
        return result;
    }

    private void backtracking(int[] nums, boolean[] used) {
        int length = nums.length;
        if (path.size() == length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < length; i++) {
            //如果当前索引元素已被使用，那直接跳过
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            if (!used[i]) {
                path.add(nums[i]);
                used[i] = true;
                backtracking(nums, used);
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}
